package com.yxt.qmgf.number.ctrl;

import com.yxt.qmgf.number.service.sudokuService;
import com.yxt.qmgf.number.vo.GameConfig;
import com.yxt.qmgf.number.vo.GameState;
import com.yxt.qmgf.number.vo.ScoreRecord;
import com.yxt.qmgf.userinfo.vo.UserInfoVO;
import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
import javafx.util.Duration;

public class SudokuGameController {
    @FXML private GridPane gameGrid;
    @FXML private Label timeLabel;
    @FXML private Label mistakesLabel;
    @FXML private Label messageLabel;

    private sudokuService sudokuService;
    private GameState gameState;
    private Timeline timer;
    private int secondsElapsed = 0;
    private UserInfoVO user;
    private TextField[][] cells = new TextField[9][9];
    private Stage gameStage;

    public void initGame(GameConfig config, UserInfoVO user, Stage gameStage) {
        this.user = user;
        this.gameStage = gameStage;
        this.sudokuService = new sudokuService();

        // 初始化游戏状态
        gameState = sudokuService.generateNewGame(config);
        initializeGameBoard();

        // 初始化计时器
        startTimer();

        // 设置窗口关闭事件
        gameStage.setOnCloseRequest(event -> {
            stopTimer();
        });
    }

    private void initializeGameBoard() {
        gameGrid.getChildren().clear();

        for (int row = 0; row < 9; row++) {
            for (int col = 0; col < 9; col++) {
                TextField cell = createSudokuCell(row, col);
                cells[row][col] = cell;
                gameGrid.add(cell, col, row);
            }
        }

        updateBoard();
    }

    private TextField createSudokuCell(int row, int col) {
        TextField cell = new TextField();
        cell.setPrefSize(40, 40);
        cell.setStyle(getCellStyle(row, col));

        // 初始数字不可编辑
        if (gameState.getBoard()[row][col] != 0) {
            cell.setText(String.valueOf(gameState.getBoard()[row][col]));
            cell.setEditable(false);
            cell.setStyle(getCellStyle(row, col) + "-fx-font-weight: bold; -fx-background-color: #f0f0f0;");
        } else {
            // 限制输入为1-9的数字
            cell.textProperty().addListener((observable, oldValue, newValue) -> {
                if (!newValue.matches("[1-9]?")) {
                    cell.setText(oldValue);
                } else if (!newValue.isEmpty()) {
                    handleCellInput(row, col, Integer.parseInt(newValue));
                }
            });
        }

        return cell;
    }

    private String getCellStyle(int row, int col) {
        String style = "-fx-font-size: 16px; -fx-alignment: center; ";

        // 添加3x3宫格边框
        if (row % 3 == 0) style += "-fx-border-width: 2 1 1 1; ";
        else if (row % 3 == 2) style += "-fx-border-width: 1 1 2 1; ";
        else style += "-fx-border-width: 1 1 1 1; ";

        if (col % 3 == 0) style += "-fx-border-width: 1 1 1 2; ";
        else if (col % 3 == 2) style += "-fx-border-width: 1 2 1 1; ";
        else style += "-fx-border-width: 1 1 1 1; ";

        style += "-fx-border-color: #000000; ";
        return style;
    }

    private void handleCellInput(int row, int col, int value) {
        if (value == gameState.getSolution()[row][col]) {
            // 答案正确
            gameState.getBoard()[row][col] = value;
            cells[row][col].setEditable(false);
            cells[row][col].setStyle(getCellStyle(row, col) + "-fx-font-weight: bold; -fx-background-color: #e6ffe6;");

            // 检查游戏是否完成
            if (sudokuService.isGameComplete(gameState.getBoard())) {
                gameCompleted();
            }
        } else {
            // 答案错误
            gameState.incrementMistakes();
            mistakesLabel.setText("错误: " + gameState.getMistakes());
            cells[row][col].setStyle(getCellStyle(row, col) + "-fx-background-color: #ffe6e6;");
        }
    }

    private void startTimer() {
        secondsElapsed = 0;
        updateTimeLabel();

        timer = new Timeline(new KeyFrame(Duration.seconds(1), e -> {
            secondsElapsed++;
            updateTimeLabel();
        }));
        timer.setCycleCount(Animation.INDEFINITE);
        timer.play();
    }

    private void stopTimer() {
        if (timer != null) {
            timer.stop();
        }
    }

    private void updateTimeLabel() {
        int minutes = secondsElapsed / 60;
        int seconds = secondsElapsed % 60;
        timeLabel.setText(String.format("用时: %02d:%02d", minutes, seconds));
    }

    private void updateBoard() {
        for (int row = 0; row < 9; row++) {
            for (int col = 0; col < 9; col++) {
                TextField cell = cells[row][col];
                if (gameState.getBoard()[row][col] != 0) {
                    cell.setText(String.valueOf(gameState.getBoard()[row][col]));
                }
            }
        }
    }

    private void gameCompleted() {
        stopTimer();
        messageLabel.setText("恭喜完成游戏！");

        // 保存分数记录
        sudokuService.saveScore(user,
                gameState.getDifficulty(),
                secondsElapsed,
                gameState.getMistakes()
        );

        // 显示完成消息
        showCompletionAlert();
    }

    private void showCompletionAlert() {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle("游戏完成");
        alert.setHeaderText("恭喜您完成数独游戏！");
        alert.setContentText(String.format(
                "用时: %d秒\n错误次数: %d",
                secondsElapsed,
                gameState.getMistakes()
        ));
        alert.showAndWait();
    }

    @FXML
    private void back() {
        stopTimer();
        gameStage.close();
    }
}